/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.business.bashe;

import java.io.FileWriter;

import han.bifang.common.exception.BifangErrorCode;
import han.bifang.common.exception.BifangException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import v1.log.bifang.han.LogQueryRequestDocument;
import v1.log.bifang.han.LogQueryResponseDocument;
import v1.log.bifang.han.RetryRequestDocument;
import v1.log.bifang.han.RetryResponseDocument;
import v1.message.bashe.han.BasheErrorDocument;
import v1.sync.web.bifang.han.SyncRequestDocument;
import v1.sync.web.bifang.han.SyncRequestDocument.SyncRequest.Clear.Type;

/**
 * @Author Kent
 */
public class BasheClient {

	private static Log log = LogFactory.getLog(BasheClient.class);

	public static LogQueryResponseDocument query(LogQueryRequestDocument req,
			String url, int timeout) throws BifangException {
		try {
			String res = basheCall(req.toString(), url, timeout);
			LogQueryResponseDocument ret = LogQueryResponseDocument.Factory
					.parse(res);
			
			FileWriter fw = new FileWriter("e:/test.xml");
			fw.write(res);
			fw.close();
			if (!ret.validate()) {
				Log log = LogFactory.getLog(BasheClient.class);
				log.error("Bashe return invalid format query response xml");
				log.error(res);
				throw new BifangException(BifangErrorCode.ACCESS_BASHE_ERROR,
						"Bashe response xml format error");
			}

			return ret;

		} catch (Exception e) {
			if (e instanceof BifangException) {
				throw (BifangException) e;
			}
			// Log log = LogFactory.getLog(BifangClient.class);
			// log.error("query Bifang error", e);
			throw new BifangException(BifangErrorCode.ACCESS_BASHE_ERROR,
					"query Bashe error", e);

		}

	}
	
	public static RetryResponseDocument retry(RetryRequestDocument reqDoc, String url, int timeout)throws BifangException{
		try {
			String res = basheCall(reqDoc.toString(), url, timeout);
			RetryResponseDocument ret = RetryResponseDocument.Factory
					.parse(res);
			if (!ret.validate()) {
				Log log = LogFactory.getLog(BasheClient.class);
				log.error("Bashe return invalid format retry response xml");
				log.error(res);
				throw new BifangException(BifangErrorCode.ACCESS_BASHE_ERROR,
						"Bashe response xml format error");
			}

			return ret;

		} catch (Exception e) {
			if (e instanceof BifangException) {
				throw (BifangException) e;
			}
			// Log log = LogFactory.getLog(BifangClient.class);
			// log.error("query Bifang error", e);
			throw new BifangException(BifangErrorCode.ACCESS_BASHE_ERROR,
					"retry Bashe error", e);

		}
	}

	public static void sync(SyncRequestDocument reqDoc, String url, int timeout)throws BifangException{
		try {
			String res = basheCall(reqDoc.toString(), url, timeout);

		} catch (Exception e) {
			if (e instanceof BifangException) {
				throw (BifangException) e;
			}
			// Log log = LogFactory.getLog(BifangClient.class);
			// log.error("query Bifang error", e);
			throw new BifangException(BifangErrorCode.ACCESS_BASHE_ERROR,
					"retry Bashe error", e);

		}
	}
	
	
	
	private static String basheCall(String req, String url, int timeout)
			throws BifangException {
		try {
			log.info("query request is " + req);
			HttpClient httpclient = new HttpClient();
			PostMethod post = new PostMethod(url);

			HttpClientParams params = new HttpClientParams();
			params.setSoTimeout(timeout * 1000);
			httpclient.setParams(params);

			RequestEntity entity = new StringRequestEntity(req.toString(),
					"text/xml", "UTF-8");
			post.setRequestEntity(entity);

			int result = httpclient.executeMethod(post);
			if (result != 200) {
				String xml = post.getResponseBodyAsString();

				throw new BifangException(BifangErrorCode.ACCESS_BASHE_ERROR,
						"Bashe returns HTTP code " + result
								+ ", return data is \n" + xml);
			}
			String res = post.getResponseBodyAsString();
			log.info("query response is " + res);
			
			if (res.startsWith("<BasheError")) {
				BasheErrorDocument errDoc = BasheErrorDocument.Factory
						.parse(res);
				if (errDoc.validate()) {
					throw new BifangException(errDoc.getBasheError()
							.getErrorCode(), errDoc.getBasheError()
							.getErrorMsg()
							+ errDoc.getBasheError().getErrorTrace());
				}

			}

			return res;

		} catch (Exception e) {
			if (e instanceof BifangException) {
				throw (BifangException) e;
			}
			// Log log = LogFactory.getLog(BifangClient.class);
			// log.error("query Bifang error", e);
			throw new BifangException(BifangErrorCode.ACCESS_BASHE_ERROR,
					"access Bashe error", e);

		}
	}

}
